package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import com.example.forum.utils.MessageUtils;
import javax.validation.constraints.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@Api(tags = "回复接口")
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleReplyService articleReplyService;

    @Resource
    private IArticleService articleService;

    @Resource
    private MessageUtils messageUtils;

    @ApiOperation("回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, @ApiParam("文章id") @RequestParam("articleId") @NotNull Long articleId,
                            @ApiParam("回复正文内容") @RequestParam("content") @NotNull String content){
        //获取用户信息
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取要回复的帖子对象
        Article article=articleService.selectById(articleId);
        //校验帖子状态
        if(article==null||article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //校验通过 执行Service  构建对象
        ArticleReply articleReply=new ArticleReply();
        articleReply.setArticleId(article.getId());
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        
        // 创建评论
        articleReplyService.create(articleReply);
        
        // 发送评论消息通知给文章作者（如果评论者不是作者自己）
        if (!user.getId().equals(article.getUserId())) {
            try {
                messageUtils.sendCommentMessage(user, article.getUserId(), article.getId(), article.getTitle(), content);
                log.info("已发送评论消息通知: 用户{}评论了文章{}", user.getId(), article.getId());
            } catch (Exception e) {
                // 消息发送失败不影响评论操作
                log.error("发送评论消息通知失败", e);
            }
        }
        
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("查询指定文章的回复表")
    @GetMapping("/getReplies")
    public AppResult selectByArticleId(HttpServletRequest request, @ApiParam("帖子id") @RequestParam("articleId") @NotNull Long articleId){
        // 首先检查文章是否存在
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        
        // 不需要检查用户登录状态，允许匿名访问
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        
        // 处理评论数据，确保前端所需的字段可用
        for (ArticleReply reply : articleReplies) {
            // 如果用户信息存在，则添加nickname和avatar字段
            if (reply.getUser() != null) {
                // 前端期望直接使用nickname和avatar字段
                reply.getUser().setAvatarUrl(reply.getUser().getAvatarUrl());
                // 如果没有昵称，使用用户名作为替代
                if (reply.getUser().getNickname() == null || reply.getUser().getNickname().isEmpty()) {
                    reply.getUser().setNickname(reply.getUser().getUsername());
                }
            }
        }
        
        //查询成功 返回结果
        return AppResult.success(articleReplies);
    }
    
    @ApiOperation("查询用户发表的所有评论")
    @GetMapping("/getByUserId")
    public AppResult selectByUserId(
            @ApiParam("用户id") @RequestParam("userId") @NotNull Long userId,
            @ApiParam("页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @ApiParam("每页条数") @RequestParam(value = "size", defaultValue = "10") Integer size) {
        
        // 验证用户ID是否有效
        if (userId == null || userId <= 0) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        
        // 调用Service层方法获取用户评论
        List<ArticleReply> userReplies = articleReplyService.selectByUserId(userId, page, size);
        
        // 获取总评论数
        Integer total = articleReplyService.countByUserId(userId);
        
        // 构建返回结果对象，包含评论列表和总数
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("items", userReplies);
        resultMap.put("total", total);
        
        // 返回包装好的结果
        return AppResult.success(resultMap);
    }
    
    @ApiOperation("删除评论")
    @PostMapping("/delete")
    public AppResult deleteReply(HttpServletRequest request, @ApiParam("评论id") @RequestParam("id") @NotNull Long id) {
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        // 检查用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        
        try {
            // 获取评论详情，检查是否存在
            ArticleReply reply = articleReplyService.getById(id);
            if (reply == null || reply.getDeleteState() == 1) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE, "评论不存在或已被删除");
            }
            
            // 检查权限：只有评论作者或文章作者或管理员可以删除评论
            Article article = articleService.selectById(reply.getArticleId());
            if (!reply.getPostUserId().equals(user.getId()) && 
                !article.getUserId().equals(user.getId()) && 
                user.getIsAdmin() != 1) {
                return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED, "没有权限删除此评论");
            }
            
            // 执行删除
            articleReplyService.deleteById(id);
            
            return AppResult.success();
        } catch (Exception e) {
            log.error("删除评论失败", e);
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
    }
    
    @ApiOperation("删除评论 (REST风格)")
    @DeleteMapping("/delete/{id}")
    public AppResult deleteReplyRest(HttpServletRequest request, @ApiParam("评论id") @PathVariable("id") @NotNull Long id) {
        // 调用已有的POST方法实现，避免代码重复
        return deleteReply(request, id);
    }
}

